package com.twb.auth.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.twb.auth.entity.verifyCode.VerifyImgCodeDto;
import com.twb.auth.service.IVerifyCodeService;
import com.twb.core.cache.redis.RedisUtil;
import com.twb.core.config.TwbConfigProperties;
import com.twb.core.exception.ServiceException;
import com.twb.core.util.CaptchaUtil;

import cn.hutool.core.codec.Base64;

/**
 * @author DSY
 * @ClassName VerifyCodeService
 * @Description 验证码
 * @date 2022年6月23日 下午1:53:45
 */
@Service("verifyCodeService")
public class VerifyCodeService implements IVerifyCodeService {

  private static final Logger logger = LoggerFactory.getLogger(VerifyCodeService.class);

  private static final String VERIFY_IMG_CODE = "verifyImgCode";

  @Value("${twb.verifyCode.timeOut}")
  private Long timeOut = 180L;
  @Value("${twb.verifyCode.length}")
  private Integer codeLength = 4;

  @Autowired
  private RedisUtil redisUtil;
  @Autowired
  private TwbConfigProperties twbConfigProperties;

  private String getVerifyCodeImgRedisKey() {
    return twbConfigProperties.getCachePrefix() + ":" + VERIFY_IMG_CODE;
  }

  @Override
  public VerifyImgCodeDto generate(int width, int height) throws IOException {
    VerifyImgCodeDto verifyCode = null;
    try (
        // 将流的初始化放到这里就不需要手动关闭流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
      String code = CaptchaUtil.outputVerifyImage(width, height, baos, codeLength);
      verifyCode = new VerifyImgCodeDto();
      String uuid = UUID.randomUUID().toString();
      verifyCode.setUnionCode(uuid);
      redisUtil.set(getVerifyCodeImgRedisKey() + ":" + uuid, code, timeOut, TimeUnit.SECONDS);
      verifyCode.setImgBytes("data:image/png;base64," + Base64.encode(baos.toByteArray()));
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      verifyCode = null;
    }
    return verifyCode;
  }

  @Override
  public Boolean verifyImgCode(String unionCode, String imgCode) throws IOException {
    String key = getVerifyCodeImgRedisKey() + ":" + unionCode;
    String code = redisUtil.get(key);
    if (StringUtils.isEmpty(code)) {
      throw new ServiceException("图形验证码已失效");
    }
    if (!code.toUpperCase().equals(imgCode.toUpperCase())) {
      throw new ServiceException("图形验证码错误");
    }
    redisUtil.delete(key);
    return true;
  }
}
